﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using StackExchange.Redis;
using WebApplication2.Common;
using WebApplication2.DB;
using WebApplication2.Models;

namespace WebApplication2.Controllers
{
    public class HomeController : Controller
    {
        private readonly EfContext _dataContext;
        private readonly RedisHelper _redis;
        private readonly IModel _channel;
        private readonly IConfiguration _configuration;
        public HomeController(EfContext dataContext, IConfiguration configuration)
        {
            _dataContext = dataContext;
            _redis = new RedisHelper();
            //创建mq队列
            //订阅消息
            _channel = new RabbitmqHelper().CreateConnection();
            _configuration = configuration;
        }
        public IActionResult Start()
        {
            _dataContext.Database.ExecuteSqlCommand("delete from Orders");
            if (!_dataContext.Users.Any())
            {
                List<Users> user = new List<Users>();
                for (var i = 0; i < 10000; i++)
                {
                    user.Add(new Users()
                    {
                        ID = Guid.NewGuid(),
                        UserName = RandomName.getRandomName()
                    });
                }
                _dataContext.Users.AddRange(user);
            }
            var goodsid = Guid.Parse("89a84ea7-4f4b-4faa-8306-5be28c2f3187");
            var stock = 100000;
            _dataContext.Goods.RemoveRange(_dataContext.Goods);
            _dataContext.SaveChanges();
            _dataContext.Goods.Add(new Goods()
            {
                ID = goodsid,
                Name = "旺仔牛奶",
                Stock = stock
            });
            _redis.HashSet("Goods", goodsid.ToString(), stock);
            _dataContext.SaveChanges();
            return Content($"初始化完成,{_configuration["server.urls"]}");
        }

        public IActionResult Index()
        {
            return View(_dataContext.Users.ToList());
        }
        
        public IActionResult Buy(Guid userId)
        {
            int code = 0;
            var bumber = _redis.HashDecrement("Goods", "89a84ea7-4f4b-4faa-8306-5be28c2f3187");
            if (bumber >= 0)
            {
                code = 1;
            }
            else
            {
                _redis.HashDelete("Goods", "89a84ea7-4f4b-4faa-8306-5be28c2f3187");
            }
            if (code == 1)
            {
                Task.Run(() =>
                {
                    //_redis.Publish("orders", new Orders()
                    //{
                    //    GoodsId = Guid.Parse("89a84ea7-4f4b-4faa-8306-5be28c2f3187"),
                    //    UserId = userId,
                    //    HisStorck = Convert.ToInt32(bumber)
                    //});
                    RabbitmqHelper.SendMessage(new Orders()
                    {
                        GoodsId = Guid.Parse("89a84ea7-4f4b-4faa-8306-5be28c2f3187"),
                        UserId = userId,
                        HisStorck = Convert.ToInt32(bumber)
                    });
                });
            }
            return Json(new { code = code });
        }
        public IActionResult GetBuyResult(Guid userId)
        {
            var goodsid = Guid.Parse("89a84ea7-4f4b-4faa-8306-5be28c2f3187");
            return Json(_dataContext.Orders.FirstOrDefault(x => x.UserId == userId && x.GoodsId == goodsid) ??
                        new Orders());
        }

    }
}
